<template>
  <div>
    <el-form :model="article">
      <el-form-item label="文章标题">
        <el-input
          type="text"
          placeholder="请填写文章标题"
          v-model="article.title"
        ></el-input>
      </el-form-item>
      <el-form-item label="分类">
        <el-select v-model="article.classifyId">
          <el-option label=".NET" :value="1" />
          <el-option label="Web" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="浏览量">
        <el-input
          type="number"
          placeholder="浏览量"
          v-model="article.browseCount"
        ></el-input>
      </el-form-item>
      <el-form-item label="点赞量">
        <el-input
          type="number"
          placeholder="点赞量"
          v-model="article.supportCount"
        ></el-input>
      </el-form-item>
      <el-form-item label="收藏量">
        <el-input
          type="number"
          placeholder="收藏数量"
          v-model="article.collectCount"
        ></el-input>
      </el-form-item>
      <el-form-item label="分享数量">
        <el-input
          type="number"
          placeholder="分享数量"
          v-model="article.shareCount"
        ></el-input>
      </el-form-item>
      <el-form-item label="封面图">
        <el-upload
          ref="upload"
          action=""
          :multiple="false"
          :show-file-list="false"
          :auto-upload="true"
          :http-request="upload"
        >
          <el-button slot="trigger" size="small" type="primary"
            >上传图片</el-button
          >

          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload>
        <div>
          <img
            :src="$cosImageUrl + article.coverImage"
            v-if="article.coverImage && isUploadNewImg == false"
            style="width: 400px"
            alt=""
          />
          <img v-else :src="article.coverImage" alt="" style="width: 400px" />
        </div>
      </el-form-item>
      <el-form-item label="状态">
        <!-- 单选按钮 -->
        <el-radio-group v-model.number="article.state">
          <el-radio :label="0">待审核</el-radio>
          <el-radio :label="1">审核中</el-radio>
          <el-radio :label="2">审核通过</el-radio>
          <el-radio :label="3">审核不通过</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 内容，富文本编辑器 -->
      <el-form-item label="文章内容"> </el-form-item>
      <el-form-item>
        <div style="border: 1px solid #ccc">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 500px; overflow-y: hidden"
            v-model="article.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="onCreated"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <div class="edit-dialog-footer">
          <el-button @click="$emit('close')">取消</el-button>
          <el-button type="primary" @click="save">立即更新</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { updateArticle, getArticle } from "@/api/article/index";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { fileConvertBase64 } from "@/utils/util";

export default {
  components: { Editor, Toolbar },
  props: {
    id: 0,
  },
  data() {
    return {
      isUploadNewImg: false, //是否上传了新的图片
      article: {
        title: "",
        classifyId: "",
        browseCount: 0,
        supportCount: 0,
        collectCount: 0,
        shareCount: 0,
        state: 1,
        content: "",
        coverImage: "",
      },
      // 编辑器属性
      editor: null,
      // 编辑器工具栏配置
      toolbarConfig: {},
      // 编辑器配置
      editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {
          uploadImage: {
            // 上传图片的配置
            // server: "https://www.xywl123.cn:5656/api/upload/article/UploadEditorPicture",
            server: this.$baseApiUrl + "article/Upload/EditorPicture",
            // 单个文件的最大体积限制，默认为 2M
            maxFileSize: 5 * 1024 * 1024, // 5M
            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
            allowedFileTypes: ["image/*"],
            // 小于该值就插入 base64 格式（而不上传），默认为 0
            // base64LimitSize: 50 * 1024, // 50kb
            headers: {
              Authorization: "Bearer " + this.$config.getToken(),
            },
            // 上传之前触发
            // onBeforeUpload(file: File) { // TS 语法
            onBeforeUpload(file) {
              // JS 语法
              // file 选中的文件，格式如 { key: file }
              return file;

              // 可以 return
              // 1. return file 或者 new 一个 file ，接下来将上传
              // 2. return false ，不上传这个 file
            },

            // 上传进度的回调函数
            // onProgress(progress: number) {
            // TS 语法
            onProgress(progress) {
              // JS 语法
              // progress 是 0-100 的数字
              console.log("progress", progress);
            },

            // 单个文件上传成功之后
            // onSuccess(file: File, res: any) {
            // TS 语法
            onSuccess(file, res) {
              // JS 语法
              // res.data.url = "https://localhost:5656/" + res.data.url;
              console.log(`${file.name} 上传成功`, res);
            },

            // 单个文件上传失败
            // onFailed(file: File, res: any) {
            // TS 语法
            onFailed(file, res) {
              // JS 语法
              console.log(`${file.name} 上传失败`, res);
            },

            // 上传错误，或者触发 timeout 超时
            // onError(file: File, err: any, res: any) {
            // TS 语法
            onError(file, err, res) {
              // JS 语法
              console.log(`${file.name} 上传出错`, err, res);
            },
          },
        },
      },
      mode: "default", // or 'simple'
    };
  },
  // 页面创建时生命周期
  created() {
    console.log(this.id);
    if (this.id <= 0 || this.id == undefined) {
      this.$message.error("id参数异常！");
      return;
    }

    getArticle(this.id)
      .then((res) => {
        console.log("获取文章详情信息：", res);

        if (res.code != 200) {
          this.$message.error(res.message);
          return;
        }

        this.article = res.data;
      })
      .catch((err) => {
        console.log(err);
      });
  },
  mounted() {},
  methods: {
    // 上传封面图
    upload(params) {
      console.log("上传回调：", params);
      fileConvertBase64(params.file, (base64) => {
        this.article.coverImage = base64;
        this.isUploadNewImg = true;
      });
    },
    // 保存文章
    save() {
      this.$message.success("立即更新文章");
      updateArticle(this.article)
        .then((res) => {
          console.log(res);

          if (res.data) {
            this.$message.success(res.message);
            this.$emit("close");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
    },
    beforeDestroy() {
      const editor = this.editor;
      if (editor == null) return;
      editor.destroy(); // 组件销毁时，及时销毁编辑器
    },
  },
};
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss" scoped>
.edit-dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>